#!/usr/bin/env python
# encoding: utf-8
"""
#-------------------------------------------------------------------#
#                   CONFIDENTIAL --- CUSTOM STUDIOS                 #     
#-------------------------------------------------------------------#
#                                                                   #
#                   @Project Name : 全球法律在线项目                #
#                                                                   #
#                   @File Name    : pdfconverter.py.py                      #
#                                                                   #
#                   @Programmer   : 李建                            #
#                                                                   #  
#                   @Start Date   : 2020-10-15 11:35                 #
#                                                                   #
#                   @Last Update  : 2020-10-15 11:35                 #
#                                                                   #
#-------------------------------------------------------------------#
# Classes:用于将pdf转换为png再合并为pdf格式，用于解除pdf的访问限制    #
#                                                                   #
#-------------------------------------------------------------------#
"""
# -*- coding: utf-8 -*-
import os
import re
import shutil

import fitz
from fpdf import FPDF
from PIL import Image

pdf_dir = []


def get_file():
    package = input("请输入pdf文件夹路径: ")
    try:
        package_path = package
    except:
        print("input error")
    docunames = os.listdir(package_path)
    for docuname in docunames:
        if os.path.splitext(docuname)[1] == '.pdf':  # 目录下名称包含.pdf的文件
            pdf_dir.append(docuname)
    return package_path


def conver_img(package_path):
    """将目标文件夹下的pdf文件切割成png图片格式并重新组合为pdf"""
    os.chdir(package_path)  # 切换到需要处理的文件夹下
    j = 0
    n = 0
    for pdf in pdf_dir:
        j = j + 1
        print("\r正在处理第%d个" % j, end="")
        try:
            doc = fitz.open(pdf)
            pdf_name = os.path.splitext(pdf)[0]
            PNGname = []
            i = 0
            for pg in range(doc.pageCount):
                i = i + 1
                page = doc[pg]
                rotate = int(0)
                # 每个尺寸的缩放系数为4，这将为我们生成分辨率提高16倍的图像。
                zoom_x = 4.0
                zoom_y = 4.0
                trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
                pm = page.getPixmap(matrix=trans, alpha=False)
                PNGnamei = pdf_name + '_' + str(i) + '.png'
                PNGname.append(PNGnamei)
                pm.writePNG(PNGnamei)
            pdf_path = pdf_name + '_p.pdf'
            makePdf(pdf_path, PNGname)
        except:
            n = n + 1
            with open('pdferror.txt', 'a', encoding='utf-8') as f:
                f.write(str(n) + '    ' + pdf + '\n')


def makePdf(pdfFileName, listPages):
    """图片转PDF"""
    fp = open(listPages[0], 'rb')  # 使用文件句柄打开图片方便关闭文件
    cover = Image.open(fp)
    width, height = cover.size  # 获取图片尺寸
    pdf = FPDF(unit="pt", format=[width, height])
    for page in listPages:  # 将图片加入pdf
        pdf.add_page()
        pdf.image(page, 0, 0)
    pdf.output(pdfFileName, "F")
    pdf.close()
    fp.close()
    path_now = os.getcwd()
    for page in listPages:  # 删除图片
        page_path = path_now + '\\' + page
        os.remove(page_path)
    file_path = path_now + '/' + pdfFileName
    pdf_path = path_now + '/pdf'
    new_pdfpath = pdf_path + '/' + pdfFileName
    new_pdffile = re.sub(r'''_p.pdf''', r'''.pdf''', new_pdfpath)
    # 新的pdf文件路径
    if not os.path.exists(pdf_path):
        os.makedirs(pdf_path)
    shutil.copy(file_path, new_pdffile)  # 将当前文件夹下新生成的pdf转移的对应目录下
    os.remove(file_path)  # 删除该文件夹下的文件


if __name__ == '__main__':
    deal_package = get_file()
    conver_img(deal_package)
